var selected_data_ids = new Array();

$(function(){
	initInfSelectBox();
	initEnvAndUrl();
//	initImportanceSelectBox();
	initTable();
//	$(window.parent)
	$(window).bind("scroll", function () {  
        var sTop = $(window).scrollTop();  
        var sTop = parseInt(sTop); 
        //下拉时如果接口参数被掩盖就弹出参数层供使用，如果函数按钮被覆盖那么弹出函数按钮层供使用
        if ($("#interparamsTbody").length > 0) {
            var paramsdivlen = $("#interparamsTbody").offset().top;
            var functiondivlen = $("#funcselectionDiv").offset().top - $("#selectParamsDiv").height();   
        	if (sTop >= paramsdivlen && sTop < functiondivlen) {           	
                if (!$("#selectIconDiv").is(":visible")) {  
                    try {  
                        $("#selectIconDiv").slideDown();  
                    } catch (e) {  
                        $("#selectIconDiv").show();  
                    }                        
                } 
                if ($("#selectFunctionDiv").is(":visible")) {  
                    try {  
                        $("#selectFunctionDiv").slideUp();  
                    } catch (e) {  
                        $("#selectFunctionDiv").hide();  
                    }                         
                }
            }
        	else if(sTop >= functiondivlen){  
                 if (!$("#selectFunctionDiv").is(":visible")) {  
                     try {  
                         $("#selectFunctionDiv").slideDown();  
                     } catch (e) {  
                         $("#selectFunctionDiv").show();  
                     }                        
                 }
             } 
            else {  
                if ($("#selectIconDiv").is(":visible")) { 
                    try {  
                        $("#selectIconDiv").slideUp();  
                    } catch (e) {  
                        $("#selectIconDiv").hide();  
                    }                         
                }  
            } 
        } 
    }); 
});
/**
 * 初始化环境和URL
 */
function initEnvAndUrl() {
	$.ajax({
		url : "/smarttest-frontstage/autog7/getTestUrl.action",
		data : {},
		method : 'POST',
		async:false,
		error:function(response,error){
			dialog('error','error'+response.status,3000);
			}, 
		success : function(data) {
			$("#environment").html(data.data);
		}
	 });
	var env = document.getElementById("environment");
	showURL(env);
	showModules(env);
}

function initTable(){
	$("#checkAll").click(function() {
		if (this.checked == true) {
			selected_data_ids = [];
			$(".checkTestData").each(function() {
				this.checked = true;
				var pulled = $(this).parent().parent();
				selected_data_ids.push(pulled);
			});
		} else {
			$(".checkTestData").each(function() {
				this.checked = false;
			});
			selected_data_ids = [];
		}
	});
}

function initInfSelectBox(){
	var code = -1;
	$.ajax({
		url : "/smarttest-frontstage/openapi/searchInfs.action",
		data : { searchValue : '' },
		method : 'POST',
		async:false,
		success : function(data) {
			if (data.status == 200 && data.data) {
				var html = "<option value=\"\" selected=\"selected\">-请选择-</option><option value=\"\" onclick=\"$('#myModal').modal();\">-添加-</option>";
				for(var i=0;i<data.data.length;i++){
					 var value = data.data[i];
					 var defined = "";
					 if (value.selfdefined == true) {
						 defined = "defined=\"self\"";
					 }
					 html += "<option value=\""+value.id+"\" "
					 	+defined
					 	+">"
						+ value.name
						+ "</option>";
				}
				$("#interface").empty();
				$("#interface").html(html);
				code = 0;
		     }
		}
	 });
	return code;
}
/**
 * 选择接口，展示接口详情
 * @param element
 */
function getParams1(element) {
	var e = $(element);
	var id = e.val();
	if (isStrEmpt(id)) {
		$("#params").html("");
		 $("#selectParamsDiv").html("");
	}
	else{
		var defined = String(e.find("option:selected").attr("defined"));
		var intername = e.find("option:selected").text();
		$.ajax({
			url : "/smarttest-frontstage/openapi/searchInfDetail.action",
			data : { cid : id ,defined:defined},
			method : 'POST',
			success : function(data) {
				if (data.status == 200 && data.data) {
					for(var i=0;i<data.data.length;i++){
						var value = data.data[i];
						 if(value&&value.param){
							testJson = eval("(" + value.param + ")");
							var selectParamsDiv = "";
						     var paramsdetails = "<table class=\"table table-striped table-bordered table-hover has-tickbox\" style=\"table-layout:fixed\">" +
								"<thead><tr><th style=\"width:30%;text-align: center;\">参数名</th><th style=\"width:10%;text-align: center;\">必选</th><th style=\"width:10%;text-align: center;\">类型</th><th style=\"width:50%;text-align: center;\">说明</th></tr></thead>"+
								"<tbody id=\"interparamsTbody\">"
							 for(var j = 0;j<testJson.length;j++){
								 var item = testJson[j];
								 paramsdetails+="<tr>"
								 paramsdetails+="<td style=\"\"><a id=\""+item.name+"\" dragtype=\"interparam\" class=\"btn btn-success\"  type=\"button\" draggable=\"true\" ondragstart=\"drag(event)\">"+item.name+"</a></td>"
								 paramsdetails+="<td style=\"\">"+item.required+"</td>"
							     paramsdetails+="<td style=\"\">"+item.type+"</td>"
							     paramsdetails+="<td style=\"\">"+item.detail+"</td>"
							     paramsdetails+="</tr>";
								 selectParamsDiv += "<a id=\""+item.name+"\" dragtype=\"interparam\" class=\"btn btn-success\"  type=\"button\" draggable=\"true\" ondragstart=\"drag(event)\">"+item.name+"</a>";
							 }
							 paramsdetails+="</tbody></table>";
							 $("#params").html(paramsdetails);
							 $("#method_value input").val(intername);
							 $("#selectParamsDiv").html(selectParamsDiv);
						 }
					}
			     }
			}
		 });
	}	
}
/**
 * 获得统一参数并包装成json格式
 * @returns {String}
 */
function getUrlParams() {
	var keys = $('.urlparam_key');
	var values = $('.urlparam_value');
	var JsonUrlParams = "{";
	for (var i = 0; i < keys.length ; i++) {
		if (JsonUrlParams != "{") {
			JsonUrlParams += ",";
		}
		JsonUrlParams += "\""+keys.eq(i).val()+"\":\""+values.eq(i).val()+"\"";
	}
	JsonUrlParams+="}";
	return JsonUrlParams;
}
/**
 * 获得当前接口的某个用例场景。并获得统一参数、接口名、接口请求、测试环境、接口场景等
 * @param element
 * @returns {Map}
 */
function getCurrentCase(element) {
	var input_checked = $(element);
//	var jsonarray_data = "[";
	var datamap = new Map();
	for (var i = 0; i < input_checked.length; i++) {
		var tr = input_checked.eq(i).parent().parent();
		var cases = input_checked.eq(i).parent().parent().children('td');
		var rmp = cases.eq(1).find('tr');
		var testdata = "{";
		if (rmp.length > 0) {
			for (var j = 0; j < rmp.length; j++) {
				if (testdata != "{") {
					testdata += ",";
				}
				var rmptd = rmp.eq(j).find('td');
				var paramval = rmptd.eq(2).children().val();
				if (paramval.startWith("{") && paramval.endWith("}")) {
					testdata += "\""+rmptd.eq(0).text()+"\":"+paramval;
				}
				else if (paramval.startWith("[") && paramval.endWith("]")) {
					testdata += "\""+rmptd.eq(0).text()+"\":"+paramval;
				}
				else {
					testdata += "\""+rmptd.eq(0).text()+"\":\""+paramval+"\"";
				}
			}		
		}
		testdata +="}";
		var code=cases.eq(2).children().val();
		var msg=cases.eq(3).children().val();
		var asserts = cases.eq(4).find('label').find('div:first a');
		var assertstr = "{";
		if (asserts.length > 0) {			
			for (var j = 0; j < asserts.length; j++) {
				if (assertstr != "{") {
					assertstr += ",";
				}
				var classname = "";
				if (asserts.eq(j).attr('classname') != undefined && asserts.eq(j).attr('classname') != 'undefined') {
					classname = asserts.eq(j).attr('classname');
				}
				assertstr += "\"k"+(j+1)+"\":\""+classname+"."+asserts.eq(j).text()+"\"";
			}
			
		}
		assertstr +="}";
		var expectnum=cases.eq(5).children().val();
		var level=cases.eq(6).find("option:selected").val();
		var details=cases.eq(7).children().val();
		var jsonObject_data = "{\"testdata\":"+testdata+",\"expectcode\":\""+code+"\",\"expectmessage\":\""+msg+"\",\"assertresult\":"+assertstr+",\"expectnum\":\""+expectnum+"\",\"testlevel\":\""+level+"\",\"testdetails\":\""+details+"\"}";
//		if (jsonarray_data != "[") {
//			jsonarray_data+=",";
//		}
//		jsonarray_data+=jsonObject_data;
		datamap.set(tr,jsonObject_data);

	}
//	jsonarray_data+="]";
//	return jsonarray_data;
	return datamap;
}
/**
 * 获得当前接口的批量用例场景。并获得统一参数、接口名、接口请求、测试环境、接口场景等
 * @returns {Map}
 */
function getCases() {
	var input_checked = $("#tbody").find('tr').find('td:first input:checked');
//	var jsonarray_data = "[";
	var datamap = new Map();
	for (var i = 0; i < input_checked.length; i++) {
		var tr = input_checked.eq(i).parent().parent();
		var cases = input_checked.eq(i).parent().parent().children('td');
		var rmp = cases.eq(1).find('tr');
		var testdata = "{";
		if (rmp.length > 0) {
			for (var j = 0; j < rmp.length; j++) {
				if (testdata != "{") {
					testdata += ",";
				}
				var rmptd = rmp.eq(j).find('td');
				testdata += "\""+rmptd.eq(0).text()+"\":\""+rmptd.eq(2).children().val()+"\"";
			}		
		}
		testdata +="}";
		var code=cases.eq(2).children().val();
		var msg=cases.eq(3).children().val();
		var asserts = cases.eq(4).find('label').find('div:first a');
		var assertstr = "{";
		if (asserts.length > 0) {			
			for (var j = 0; j < asserts.length; j++) {
				if (assertstr != "{") {
					assertstr += ",";
				}
				var classname = "";
				if (asserts.eq(j).attr('classname') != undefined && asserts.eq(j).attr('classname') != 'undefined') {
					classname = asserts.eq(j).attr('classname');
				}
				assertstr += "\"k"+(j+1)+"\":\""+classname+"."+asserts.eq(j).text()+"\"";
			}
			
		}
		assertstr +="}";
		var expectnum=cases.eq(5).children().val();
		var level=cases.eq(6).find("option:selected").val();
		var details=cases.eq(7).children().val();
		var jsonObject_data = "{\"testdata\":"+testdata+",\"expectcode\":\""+code+"\",\"expectmessage\":\""+msg+"\",\"assertresult\":"+assertstr+",\"expectnum\":\""+expectnum+"\",\"testlevel\":\""+level+"\",\"testdetails\":\""+details+"\"}";
//		if (jsonarray_data != "[") {
//			jsonarray_data+=",";
//		}
//		jsonarray_data+=jsonObject_data;
		datamap.set(tr,jsonObject_data);

	}
//	jsonarray_data+="]";
//	return jsonarray_data;
	return datamap;
}
/**
 * 删除接口参数
 * @param element
 * @returns {Boolean}
 */
function deleteInterparam(element) {
	var e = $(element).parent().parent();
	e.remove();
	return false;
}

function singleCheckData(checkbox) {
	if (checkbox.checked) {
		var val = $(checkbox).parent().parent();
		if (-1 == $.inArray(val, selected_data_ids)) {
			selected_data_ids.push(val);
		}
	} else {
		var val = $(checkbox).parent().parent();
		var i = $.inArray(val, selected_data_ids);
		if (i > -1) {
			selected_data_ids.splice(i, 1);
		}
	}
}
/**
 * 删除选中的接口场景
 */
function deleteInterfacedetails(){
	for(var i = 0;i<selected_data_ids.length;i++){
		var deleteDatas = $(selected_data_ids[i]);
		var tr_expandable = deleteDatas.next('.tr-expandable');
		deleteDatas.remove();
		tr_expandable.remove();
	}
}
/**
 * 保存用例
 */
function saveCase(){
	var ele = $(".addsetting_class:visible");
	var bol = true;
	for (var i = 0; i < ele.length; i++) {
		var form = ele.data('bootstrapValidator');
		if (form != undefined) {
			form.validate();
			bol  = 	bol && form.isValid();
		}
	}
	setTimeout(function(){
		var datas;
		if (!bol) {
			return;
		}
		else {
			var notept_td = $(".not_Empty_td:visible");
			if (notept_td.length > 0) {
				dialog('error','请正确填写所有单元格',3000);
				return;
			}
			else {
				var trs = $("#addautosetting > tr");
				var jsonstr = "[";
				for (var j = 0; j < trs.length; j++) {
					var rtype = trs.eq(j).attr("type");
					var ths = trs.eq(j).find("table th");
					var datatrs = trs.eq(j).find("table tbody tr");
					var data = "";
					for (var k = 0; k < datatrs.length; k++) {
						var dd = "";
						var tds = datatrs.eq(k).find('td');
						for (var i = 1; i < ths.length; i++) {
							if (!isStrEmpt(dd)) {
								dd += ",";
							}
							dd += "\""+ths.eq(i).attr("name")+"\":\""+tds.eq(i).text()+"\"";
						}
						dd ="{" + dd + "}";
						data += dd;
					}
					jsonstr += "{\"type\":\""+rtype+"\",\"data\":["+data+"]}";
				}
				jsonstr += "]";
				beforeSave(jsonstr);			
			}			
		}	
    },1);
}

function beforeSave(jsonstr){
	//接口
	var inf = $("#interface").find("option:selected").text();;
	//环境
	var env = $("#environment").val();
	//URL
	var url = $("#URL").attr("urlid");
	//接口类型
	var inftype = $("#intertype").val();
	//重要程度
	var degree = $("#degree").val();
	//业务模块
	var module = $("#module").val();
	//负责人
	var tester = $("#tester").val();
	//请求方式
	var reqType = $("#requestType").val();
	//outerParam
	var outerparams = getUrlParams();
	
	var dataAsUrlparam = $("#dataAsUrlparam").attr("checked")=="checked"?true:false;
	//每项数据
	var trs = $("#tbody > tr");
	var data_items = new Array();
	trs.each(function(){
		var tds = $("> td",this);
		if(tds){
			var dataItem = new Object();
			dataItem.expectcode = $("input",tds[2]).val();
			dataItem.expectmsg=$("input",tds[3]).val();
			dataItem.expectcount=$("input",tds[5]).val();
			dataItem.level = $("option:selected",tds[6]).val();
			dataItem.description = $("input",tds[7]).val();
			var params_item = $("tr",tds[1]);
			var asserts_item = $(tds[4]).find("a[class*='btn btn-info assert-details']");
			if(params_item.length>0){
				var innerparames = solveParam(params_item);
				dataItem.innerparams = innerparames;
			}else{
				//验证param
			}
		    if(asserts_item.length>0){
		    	var resultasserts = solveAssert(asserts_item);
		    	dataItem.resultasserts = resultasserts;
		    }else{
		    	//验证断言
		    }
		    data_items.push(dataItem);
		}
	});
	if(data_items.length>0){
		var str = JSON.stringify(data_items);
	$.ajax({
		url : "/smarttest-frontstage/AutoInterface/addAutoCase.action",
		data : { inf : inf, env : env, url : url, inftype : inftype, degree : degree, module : module, tester : tester, reqType : reqType, outerparams : outerparams, dataAsUrlparam : dataAsUrlparam, inits : jsonstr,dataitems : str},
		method : 'POST',
		success : function(data) {
			if (data.status == 200) {
			    dialog('succ','添加接口自动化成功',3000);
			    setTimeout(window.location.href="autog7.html", 3000);
		    }
		}
	 });
	}else{
		dialog('error','添加自动化用例失败',3000);
	}
}

var dataItem = {
    innerparams:"",
    expectcode:"",
	expectmsg:"",
	resultasserts:"",
	expectcount:1,
	level:1,
	description:""
}

function deleteparam1(element) {
	var e = $(element).parent().parent();
	e.remove();
	return false;
}

function solveParam(params){
	var testdata = "{";
	if (params.length > 0) {
		for (var j = 0; j < params.length; j++) {
			if (testdata != "{") {
				testdata += ",";
			}
			var key = $("a",params[j]).text();
			var val = $("input",params[j]).val();
			testdata += "\""+key+"\":\""+val+"\"";
		}		
	}
	testdata +="}";
	return testdata;
}

function solveAssert(asserts){
	var assertstr = "{";
	if (asserts.length > 0) {			
		for (var j = 0; j < asserts.length; j++) {
			if (assertstr != "{") {
				assertstr += ",";
			}
			var classname = $(asserts[j]).attr('classname');
			if (classname == undefined || classname == 'undefined') {
	               return;
			}
			var val = $(asserts[j]).text();
			assertstr += "\"k"+(j+1)+"\":\""+classname+"."+val+"\"";
		}
	}
	assertstr +="}";
	return assertstr;
}
/**
 * 选择不同的测试环境时展示不同的URL
 * @param element
 */
function showURL(element) {
	var env = $(element).find('option:selected').val();
	if (env == 1) {
		$("#URL").val("http://test.tx.router.huoyunren.com/router");
		$("#URL").attr("disabled","disabled");
		$("#URL").attr("urlid",1);
	}
	else if(env == 2) {
		$("#URL").val("http://demo.tx.router.huoyunren.com/router");
		$("#URL").attr("disabled","disabled");
		$("#URL").attr("urlid",2);
	}
	else if(env == 3) {
		$("#URL").val("http://tx.router.huoyunren.com/router");
		$("#URL").attr("disabled","disabled");
		$("#URL").attr("urlid",3);
	}
	else {
		$("#URL").val("");
		$("#URL").removeAttr("disabled");
		$("#URL").attr("urlid",0);
	}
}
/**
 * 执行批量接口场景的调试
 * @param cases
 */
function debugTest(cases) {
	var ele = $(".addsetting_class:visible");
	var bol = true;
	for (var i = 0; i < ele.length; i++) {
		var form = ele.data('bootstrapValidator');
		if (form != undefined) {
			form.validate();
			bol  = 	bol && form.isValid();
		}
	}
	setTimeout(function(){
		var datas;
		if (!bol) {
			return;
		}
		else {
			var notept_td = $(".not_Empty_td:visible");
			if (notept_td.length > 0) {
				dialog('error','请正确填写所有单元格',3000);
				return;
			}
			else {
				var trs = $("#addautosetting > tr");
				var jsonstr = "[";
				for (var j = 0; j < trs.length; j++) {
					var rtype = trs.eq(j).attr("type");
					var ths = trs.eq(j).find("table th");
					var datatrs = trs.eq(j).find("table tbody tr");
					var data = "";
					for (var k = 0; k < datatrs.length; k++) {
						var dd = "";
						var tds = datatrs.eq(k).find('td');
						for (var i = 1; i < ths.length; i++) {
							if (!isStrEmpt(dd)) {
								dd += ",";
							}
							dd += "\""+ths.eq(i).attr("name")+"\":\""+tds.eq(i).text()+"\"";
						}
						dd ="{" + dd + "}";
						data += dd;
					}
					jsonstr += "{\"type\":\""+rtype+"\",\"data\":["+data+"]}";
				}
				jsonstr += "]";
				var apiurl = $("#URL").val();
				var method = $("#requestType").find("option:selected").val();
				var outerparams = getUrlParams();
				var isdataAsUrlparam = $("#dataAsUrlparam").prop('checked');
				var intertype = $("#intertype").find('option:selected').val();
				var casesmap = cases;
				if (isStrEmpt(apiurl)) {
					dialog('error',"URL地址不能为空",3000);
				}
				else {		
					if (intertype == "DSP") {
						if (isStrEmpt($("#app_key").val())) {
							dialog('notice',"请输入APP_KEY",3000);
							return;
						}
						else if (isStrEmpt($("#secret").val())) {
							dialog('notice',"请输入SECRET",3000);
							return;
						}
						else {
							$("#param_appkey").val($("#app_key").val());
							var signstr = "sign2(appkey,method,format,timestamp,${jsonParams},"+$("#secret").val()+")";
							$("#param_sign").val(signstr);
						}			
					}
					//该参数代表批量执行中是否初始化数据。1代表不初始化，0代表初始化
					var tmpInit = 1;
					//每个场景都判断，如果要初始化，那么tmpInit*=0
					casesmap.forEach(function (value,key, map) {
						tmpInit *= parseInt(key.find("td:nth-child(9) select option:selected").val());
						
					});
					if (tmpInit == 0) {
						$.ajax({
							url : "/smarttest-frontstage/autog7/initData.action",
							data : {datainits:jsonstr},
							method : 'POST',
							error:function(response,error){
								dialog('error','error'+response.status,3000);
								}, 
							success : function(returns) {
								casesmap.forEach(function (value,key, map) {
									key.find("td:last").html("<img width=\"100%\" height=\"100%\" border=\"0\" src=\"img/msgbox_loading.gif\">");
									$.ajax({
										url : "/smarttest-frontstage/autog7/debugTest.action",
										data : {apiurl:apiurl,httpmethod:method,outerparams:outerparams,dataAsParams:isdataAsUrlparam,cases:value},
										method : 'POST',
										error:function(response,error){
											dialog('error','error'+response.status,3000);
											}, 
										success : function(data) {
											if (data.data.result == "PASS") {
												key.find("td:last").html("<font color=\"green\">PASS</font>" + 
														"<a class=\"table-expandable-arrow btn btn-sm\" onclick=\"launchTestResult(this);\" style=\"margin:0 auto;margin-top: 5px;\"></a>");
												if (isContains(key.next().attr('class'),'tr-expandable')) {
													key.next().remove();
												}
												key.after("<tr style=\"display: none;overflow: hidden;\" class=\"tr-expandable\"><td colspan=\"11\"> <p><font size=\"2\">接口返回&nbsp;&nbsp;:&nbsp;&nbsp;</font>"+data.data.returns+"</p></td></tr>");
												launchTestResult(key.find("td:last a").get(0));
											}
											else if (data.data.result == "FAIL") {
												key.find("td:last").html("<font color=\"red\">FAIL</font>" + 
														"<a class=\"table-expandable-arrow btn btn-sm\" onclick=\"launchTestResult(this);\" style=\"margin:0 auto;margin-top: 5px;\"></a>");
												if (isContains(key.next().attr('class'),'tr-expandable')) {
													key.next().remove();
												}
												key.after("<tr style=\"display: none;overflow: hidden;\" class=\"tr-expandable\"><td colspan=\"11\"> <p><font size=\"2\">接口返回&nbsp;&nbsp;:&nbsp;&nbsp;</font>"+data.data.returns+"</p><p><font size=\"2\">错误详情&nbsp;&nbsp;:&nbsp;&nbsp;</font><font color=\"red\">"+data.data.errmsg+"</font></p></td></tr>");
												launchTestResult(key.find("td:last a").get(0));
											}
											else if (data.data.result == "SKIP") {
												key.find("td:last").html("<font color=\"yellow\">SKIP</font>"+
														"<a class=\"table-expandable-arrow btn btn-sm\" onclick=\"launchTestResult(this);\" style=\"margin:0 auto;margin-top: 5px;\"></a>");
												if (isContains(key.next().attr('class'),'tr-expandable')) {
													key.next().remove();
												}
												key.after("<tr style=\"display: none;overflow: hidden;\" class=\"tr-expandable\"><td colspan=\"11\"> <p><font size=\"2\">接口返回&nbsp;&nbsp;:&nbsp;&nbsp;</font>"+data.data.returns+"</p><p><font size=\"2\">错误详情&nbsp;&nbsp;:&nbsp;&nbsp;</font><font color=\"red\">"+data.data.errmsg+"</font></p></td></tr>");
												launchTestResult(key.find("td:last a").get(0));
											}
										}
									 });
								}); 
							}
						});
					}
					else {
						casesmap.forEach(function (value,key, map) {
							key.find("td:last").html("<img width=\"100%\" height=\"100%\" border=\"0\" src=\"img/msgbox_loading.gif\">");
							$.ajax({
								url : "/smarttest-frontstage/autog7/debugTest.action",
								data : {apiurl:apiurl,httpmethod:method,outerparams:outerparams,dataAsParams:isdataAsUrlparam,cases:value},
								method : 'POST',
								error:function(response,error){
									dialog('error','error'+response.status,3000);
									}, 
								success : function(data) {
									if (data.data.result == "PASS") {
										key.find("td:last").html("<font color=\"green\">PASS</font>" + 
												"<a class=\"table-expandable-arrow btn btn-sm\" onclick=\"launchTestResult(this);\" style=\"margin:0 auto;margin-top: 5px;\"></a>");
										if (isContains(key.next().attr('class'),'tr-expandable')) {
											key.next().remove();
										}
										key.after("<tr style=\"display: none;overflow: hidden;\" class=\"tr-expandable\"><td colspan=\"11\"> <p><font size=\"2\">接口返回&nbsp;&nbsp;:&nbsp;&nbsp;</font>"+data.data.returns+"</p></td></tr>");
										launchTestResult(key.find("td:last a").get(0));
									}
									else if (data.data.result == "FAIL") {
										key.find("td:last").html("<font color=\"red\">FAIL</font>" + 
												"<a class=\"table-expandable-arrow btn btn-sm\" onclick=\"launchTestResult(this);\" style=\"margin:0 auto;margin-top: 5px;\"></a>");
										if (isContains(key.next().attr('class'),'tr-expandable')) {
											key.next().remove();
										}
										key.after("<tr style=\"display: none;overflow: hidden;\" class=\"tr-expandable\"><td colspan=\"11\"> <p><font size=\"2\">接口返回&nbsp;&nbsp;:&nbsp;&nbsp;</font>"+data.data.returns+"</p><p><font size=\"2\">错误详情&nbsp;&nbsp;:&nbsp;&nbsp;</font><font color=\"red\">"+data.data.errmsg+"</font></p></td></tr>");
										launchTestResult(key.find("td:last a").get(0));
									}
									else if (data.data.result == "SKIP") {
										key.find("td:last").html("<font color=\"yellow\">SKIP</font>"+
												"<a class=\"table-expandable-arrow btn btn-sm\" onclick=\"launchTestResult(this);\" style=\"margin:0 auto;margin-top: 5px;\"></a>");
										if (isContains(key.next().attr('class'),'tr-expandable')) {
											key.next().remove();
										}
										key.after("<tr style=\"display: none;overflow: hidden;\" class=\"tr-expandable\"><td colspan=\"11\"> <p><font size=\"2\">接口返回&nbsp;&nbsp;:&nbsp;&nbsp;</font>"+data.data.returns+"</p><p><font size=\"2\">错误详情&nbsp;&nbsp;:&nbsp;&nbsp;</font><font color=\"red\">"+data.data.errmsg+"</font></p></td></tr>");
										launchTestResult(key.find("td:last a").get(0));
									}
								}
							 });
						}); 
					}
								
				}				
			}			
		}	
    },1);	
}
/**
 * 选择接口类型：dsp接口统一参数只展示秘钥，其他接口默认显示系统默认的参数
 */
function selectintertype() {
	var intertype = $("#intertype").find('option:selected').val();
	var intername = "";
	if (!isStrEmpt($("#interface").find('option:selected').val())) {
		intername = $("#interface").find('option:selected').text();
	}
	if (intertype == "DSP") {
		$("#hideouter").hide();
		$("#dsp_keyandsecret").show();
		$("#hidedata").html("<table id=\"param_tb\"  style=\"width: 100%\">"+
								"<tr>"+
									"<td style=\"width: 8%;float:left;\">"+
									"<input class=\"form-control urlparam_key\" type=\"text\" value=\"app_key\">"+
									"</td>"+
									"<td align=\"center\" style=\"width: 1%;float:left;\">:</td>"+
									"<td style=\"width: 8%;float:left;\">"+
									"<input id=\"param_appkey\" dragtype=\"paramsfuction\" ondrop=\"drop(event);\" ondragover=\"allowDrop2(event);\" class=\"form-control urlparam_value\" type=\"text\" value=\"bc7e94\">"+
									"</td>"+
									"<td align=\"center\" style=\"width: 1%;float:left;\"><a onclick=\"deleteparam(this);\" href=\"####\"><img width=\"100%\" height=\"100%\" border=\"0\" src=\"img/delete.gif\"></a></td>"+
									"<td align=\"center\" style=\"width: 2%;float:left;\">|</td>"+
									"<td style=\"width: 8%;float:left;\"><input class=\"form-control urlparam_key\" type=\"text\" value=\"method\"></td>"+
									"<td align=\"center\" style=\"width: 1%;float:left;\">:</td>"+
									"<td id=\"method_value\" style=\"width: 8%;float:left;\"><input dragtype=\"paramsfuction\" ondrop=\"drop(event);\" ondragover=\"allowDrop2(event);\" class=\"form-control urlparam_value\" type=\"text\" value=\""+intername+"\"></td>"+
									"<td align=\"center\" style=\"width: 1%;float:left;\"><a onclick=\"deleteparam(this);\" href=\"####\"><img width=\"100%\" height=\"100%\" border=\"0\" src=\"img/delete.gif\"></a></td>"+
									"<td align=\"center\" style=\"width: 2%;float:left;\">|</td>"+
									"<td style=\"width: 8%;float:left;\"><input class=\"form-control urlparam_key\" type=\"text\" value=\"timestamp\"></td>"+
									"<td align=\"center\" style=\"width: 1%;float:left;\">:</td>"+
									"<td style=\"width: 8%;float:left;\"><input dragtype=\"paramsfuction\" ondrop=\"drop(event);\" ondragover=\"allowDrop2(event);\" class=\"form-control urlparam_value\" type=\"text\" value=\"now()\"></td>"+
									"<td align=\"center\" style=\"width: 1%;float:left;\"><a onclick=\"deleteparam(this);\" href=\"####\"><img width=\"100%\" height=\"100%\" border=\"0\" src=\"img/delete.gif\"></a></td>"+
									"<td align=\"center\" style=\"width: 2%;float:left;\">|</td>"+	
									"<td style=\"width: 8%;float:left;\"><input class=\"form-control urlparam_key\" type=\"text\" value=\"sign\"></td>"+
									"<td align=\"center\" style=\"width: 1%;float:left;\">:</td>"+
									"<td style=\"width: 8%;float:left;\"><input id=\"param_sign\" dragtype=\"paramsfuction\" ondrop=\"drop(event);\" ondragover=\"allowDrop2(event);\" class=\"form-control urlparam_value\" type=\"text\" value=\"sign2(appkey,method,format,timestamp,${jsonParams},88DA9E321AF1B146B758460D5D0697F8)\"></td>"+
									"<td align=\"center\" style=\"width: 1%;float:left;\"><a onclick=\"deleteparam(this);\" href=\"####\"><img width=\"100%\" height=\"100%\" border=\"0\" src=\"img/delete.gif\"></a></td>"+
									"<td align=\"center\" style=\"width: 2%;float:left;\">|</td>"+
									"<td style=\"width: 8%;float:left;\"><input class=\"form-control urlparam_key\" type=\"text\" value=\"format\"></td>"+
									"<td align=\"center\" style=\"width: 1%;float:left;\">:</td>"+
									"<td style=\"width: 8%;float:left;\"><input dragtype=\"paramsfuction\" ondrop=\"drop(event);\" ondragover=\"allowDrop2(event);\" class=\"form-control urlparam_value\" type=\"text\" value=\"json\"></td>"+
									"<td align=\"center\" style=\"width: 1%;float:left;\"><a onclick=\"deleteparam(this);\" href=\"####\"><img width=\"100%\" height=\"100%\" border=\"0\" src=\"img/delete.gif\"></a></td>"+					
								"</tr>"+
								"</table>");
		$("#hidedata").hide();
		$("#hiddeUrlToParam").hide();		
	}
	else {
		$("#hideouter").show();
		$("#dsp_keyandsecret").hide();
		$("#hidedata").show();
		$("#hiddeUrlToParam").show();	
	}
}
/**
 * 展示模块
 * @param element
 */
function showModules(element){
	var env = $(element).find('option:selected').val();
	$.ajax({
		url : "/smarttest-frontstage/AutoInterface/getModuleByEnv.action",
		method : 'POST',
		data : { id : env },
		async:false,
		success : function(data) {
			if (data.status == 200 && data.data) {
				var html = "";
				for(var i=0;i<data.data.length;i++){
					 var value = data.data[i];
					 html += "<option value=\""+value.id+"\" "
					 	+">"
						+ value.name
						+ "</option>";
				}
				$("#module").empty();
				$("#module").html(html);
		     }
		}
	 });
	showURL(element);
}

//selectAddInter(e) {
//	alert(1243);
//	var str = $(e).find("option:selected").text();
//	alert(str);
//	if (str == "-添加-") {
//		$('#myModal').modal();
//	}
//}
/**
 * 添加数据初始化
 */
function addInitData() {
	if ($("#typeselect").find('option:selected').val() == 0) {
		$("#addautosetting").append("<tr type=\"message\"><td>"+$("#msg_div").html()+"</td></tr>");
	}
	$("#initdataModal").modal('hide');
	settingFunc();
}
/**
 * 添加初始化数据项后的通用函数调用.主要是为了可编辑单元格、展示错误信息、可全选
 */
function settingFunc() {
	editrow();
	showErr();
	selectAll();
}
/**
 * 编辑行：双击可编辑，鼠标点击别处保存
 */
function editrow () {
	$("#addautosetting table td.editable").dblclick(function () {
		ShowElement(this,$(".showinfo"),$(".addsetting_class"),validata);
	});
}
/**
 * 验证数据初始化界面的数据是否合理
 */
function validata() {
	var ele = $(".addsetting_class:visible");
	for (var i = 0; i < ele.length; i++) {
		ele.eq(i).bootstrapValidator({
			message : 'This value is not valid',
			feedbackIcons : {
				valid : 'glyphicon glyphicon-ok',
				invalid : 'glyphicon glyphicon-remove',
				validating : 'glyphicon glyphicon-refresh'
			},
			fields : {
				msg_sendmethod : {
					message : '请输入参数名',
					validators : {
						notEmpty : {
							message : '不能为空'
						},
					}
				},
				msg_add : {
					message : '请选择是否必选',
					validators : {
						notEmpty : {
							message : '不能为空'
						},
					}
				},
				msg_port : {
					message : '请输入类型',
					validators : {
						notEmpty : {
							message : '不能为空'
						},
						regexp: {
	                         regexp: /^[0-9]+$/,
	                         message: '请输入正整数'
	                     }
					}
				},
				msg_sendtime : {
					message : '请输入类型',
					validators : {
						notEmpty : {
							message : '不能为空'
						},
					}
				},
				msg_startnum : {
					message : '请输入类型',
					validators : {
						regexp: {
	                         regexp: /^-?\d+$/,
	                         message: '请输入整数'
	                     }
					}
				},
				msg_count : {
					message : '请输入类型',
					validators : {
						regexp: {
	                         regexp: /^-?\d+$/,
	                         message: '请输入整数'
	                     }
					}
				},
				msg_internal : {
					message : '请输入类型',
					validators : {
						notEmpty : {
							message : '不能为空'
						},
						regexp: {
	                         regexp: /^[0-9]+$/,
	                         message: '请输入正整数'
	                     }
					}
				},
				msg_text : {
					message : '请输入类型',
					validators : {
						notEmpty : {
							message : '不能为空'
						},
					}
				},
			}
		});
	}
}
/**
 * 删除选中的接口场景
 * @param e
 */
function removeSelected(e) {
	var tb = $(e).closest("td").children("table");
	delSelected(tb);
}

/**
 * 添加报文
 * @param e
 */
function addMsg(e) {
	var tb = $(e).closest("td").children("table");
	tb.append("<tr>"+
		"<td align=\"center\"><input type=\"checkbox\"></td>"+
		"<td class=\"not_Empty_td editable\"></td>"+
		"<td class=\"not_Empty_td editable\"></td>"+
		"<td class=\"not_Empty_td editable\"></td>"+
		"<td class=\"not_Empty_td editable\"></td>"+
		"<td class=\"editable\"></td>"+
		"<td class=\"not_Empty_td editable\"></td>"+
		"<td class=\"not_Empty_td editable\"></td>"+
		"<td class=\"editable\"></td>"+
		"<td class=\"editable\"></td>"+
		"<td class=\"editable\"></td>"+
		"</tr>");
	editrow();
	showErr();
}
/**
 * 删除当前选中的数据初始化
 * @param e
 */
function delCurrentInit(e) {
	$(e).closest("tr").remove();
}
